//
//  StudyViewController.m
//  V-Learn
//
//  Created by Apple on 2018/12/20.
//  Copyright © 2018 yxk. All rights reserved.
//

#import "StudyViewController.h"
#import "NSLayoutConstraint+FF.h"
#import "LBSaomangCell.h"
#import "LBCourseOutputDTOListModel.h"
#import "LBCourseCollectVC.h"
#import "LBCoureseDetailVC.h"
#import "LBLeaveVC.h"
#import "CourseDetailsViewController.h"
// 打卡
#import "VKStudyCardController.h"
// 请假
#import "VKStudyLeaveController.h"
// 在线规划
//#import "VKStudyOnlineController.h"
// 收藏
#import "VKStudyCollectController.h"
#import "LBOnlineVC.h"
#import "WKOnlinePingguResultModel.h"
#import "LBEvaluationResultVC.h"
#import "JKScheduleView.h"
@interface StudyViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSArray *onLineDataArray;
@end

@implementation StudyViewController
{
    NSInteger  _page;
    NSInteger  _currentCount;
    NSInteger  _pageIndex;
    JKScheduleView *scheduleView;
}
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
        
    }
    return _dataArray;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -LBHeight_StatusBar, ScreenW, ScreenH-LBHeight_TabBar+LBHeight_StatusBar) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    NSString *token = [UserModel getUserModel].token;
    if (token) {
        //下拉刷新
        [self downRefreshData];
    }
    //获取打卡天数
    [self requestGetDakaDay];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self setupUI];
    self.navigationItem.title = @"学习";
    
}
- (void)downRefreshData{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadDownNewDataSecond];
    }];
    
    //2.上拉
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadUpNewDataSecond)];
    //在刷新数据覆盖不显示数据的 cell 的分割线,如果不设置,则会显示 cell 的分割线
    UIView *footView = [UIView new];
    self.tableView.tableFooterView = footView;
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark -- 下拉刷新
-(void)loadDownNewDataSecond{
    //默认页数、条数
    _page = 1;
    _currentCount = 10;
    [self requestDataMyCoureseList:_currentCount page:_page];
}
#pragma mark -- 上拉加载
-(void)loadUpNewDataSecond{
    _page++;//页数
    _currentCount = 10;
    _pageIndex = _page*_currentCount;
    [self requestDataMyCoureseList:_pageIndex page:_pageIndex];
}
- (void)requestDataMyCoureseList:(NSInteger)currentCount page:(NSInteger)page{

    NSString *token = [UserModel getUserModel].token;
    if (token) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setObject:@(page) forKey:@"page"];
        [data setObject:@(currentCount) forKey:@"num"];
        
        [data setObject:token forKey:@"token"];
        [WYHXNetWorkManager get:WKMyCoureseList_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
            NSString *code = responseObj[@"code"];
            if ([code integerValue]==200) {
                if (page == 1) {
                    [self.dataArray removeAllObjects];
                }

                NSArray *arr = [LBCourseOutputDTOListModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
                [self.dataArray addObjectsFromArray:arr];
            }
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView reloadData];
        }];
        
    }

}
- (void)requestGetDakaDay{
    NSString *token = [UserModel getUserModel].token;
    if (token) {
        
        [WYHXNetWorkManager get:WKQueryCurrentMonthClockNum_WKURL params:@{@"token":token} completionHandler:^(id responseObj, NSError *error) {
            NSString *code = responseObj[@"code"];
            if ([code integerValue]==200) {
                
                self->scheduleView.count = [responseObj[@"data"] integerValue];
            }
        }];
    }else{
        
    }
}
// 获取当月的天数
- (NSInteger)getNumberOfDaysInMonth
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]];
    NSUInteger numberOfDaysInMonth = range.length;
    
    return numberOfDaysInMonth;
}

#pragma mark - 创建子控件
- (void)setupUI{
    UIView *topView = [UIView new];
    [self.view addSubview:topView];
    topView.frame = CGRectMake(0, 0, ScreenW, 260);
    topView.backgroundColor = rgb(248,248,248);
    
    UIImageView *topImageView = [[UIImageView alloc] init];
    topImageView.image = [UIImage imageNamed:@"wk_study2"];
    topImageView.frame = CGRectMake(0, 0, ScreenW, 170);
    [topView addSubview:topImageView];
    
    scheduleView = [[JKScheduleView alloc]initWithFrame:CGRectMake(0, 30, [UIScreen mainScreen].bounds.size.width, 170)];
    scheduleView.backgroundColor = [UIColor clearColor];
    scheduleView.count = 0;
    [topImageView addSubview:scheduleView];
    
    UILabel * titleLab = [UILabel labelWithText:@"学习" andTextColor:rgb(255,255,255) andName:nil andFontSize:18];
    [topView addSubview:titleLab];
    [titleLab makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(topView);
        make.top.mas_equalTo(38);
    }];


    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = topView;
    self.tableView.tableFooterView = [UIView new];
    UIView *smallView = [UIView new];
    smallView.layer.cornerRadius = 8;
    smallView.layer.masksToBounds = YES;

    smallView.backgroundColor = [UIColor whiteColor];
    [topView addSubview:smallView];
    //如果 为ture 阴影想过出不来
    smallView.layer.masksToBounds = false;
    //设置边框颜色
    [self addShadowToView:smallView withColor:rgba(233,84,18,0.2)];
    
    [smallView makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-20);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(80);
    }];
    
    for (int i=0; i<4; i++) {
        UIView *everyView = [UIView new];
        CGFloat w = (ScreenW-15*2)/4;
        everyView.frame = CGRectMake(i*w, 0, w, 80);
        [smallView addSubview:everyView];
        NSArray *images = @[@"zxhg2",@"wk_dk",@"wk_qj",@"wk_sc"];
        NSArray *titles = @[@"在线评估",@"打卡",@"请假",@"收藏"];
        UIButton *smallButton = [[UIButton alloc] init];
        [everyView addSubview:smallButton];
        [smallButton setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
        [smallButton setTitle:titles[i] forState:UIControlStateNormal];
        [smallButton setTitleColor:rgb(51,51,51) forState:UIControlStateNormal];
        smallButton.titleLabel.font = LBFont(13);
        smallButton.frame = CGRectMake(0, 0, w, 80);
        
        smallButton.tag = 1100+i;
        [smallButton addTarget:self action:@selector(clickStudyBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        if (i==0) {
            [smallButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -18.75, -45, 0)];
            [smallButton setImageEdgeInsets:UIEdgeInsetsMake(0, 23.25, 20, 0)];
            
        }else{
            [smallButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -35, -45, 0)];
            [smallButton setImageEdgeInsets:UIEdgeInsetsMake(0, 20, 20, 0)];
        }
    }
//    if (@available(iOS 11.0, *)) {
//        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
//    }
}

#pragma mark - 首页顶部 添加四边阴影效果
- (void)addShadowToView:(UIView *)theView withColor:(UIColor *)theColor {
    // 阴影颜色
    theView.layer.shadowColor = theColor.CGColor;
    // 阴影偏移，默认(0, -3)
    theView.layer.shadowOffset = CGSizeMake(0,0);
    // 阴影透明度，默认0
    theView.layer.shadowOpacity = 0.5;
    // 阴影半径，默认3
    theView.layer.shadowRadius = 5;
    
}
- (void)gotoLoginViewController{
    LBLoginVC *loginVC = [[LBLoginVC alloc] init];
    loginVC.jumpType = @"1";
    [self.navigationController pushViewController:loginVC animated:YES];
}
#pragma mark - 点击在线 收藏 按钮点击事件
- (void)clickStudyBtn:(UIButton *)sender{
    NSInteger index = sender.tag - 1100;
    NSString *token = [UserModel getUserModel].token;

//    NSLog(@"%ld",index);
    switch (index) {
        case 0:{
            if (!token) {
                [self gotoLoginViewController];
            }else{
                __weak typeof(self)weakSelf = self;
                NSMutableDictionary *data = [NSMutableDictionary dictionary];
                [data setObject:token forKey:@"token"];
                [WYHXNetWorkManager get:WKOnLinePlan_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
                    NSString *code = responseObj[@"code"];
                    if ([code integerValue]==202) {
                        //没有规划跳转规划 页面
                        LBOnlineVC *onlineVC = [LBOnlineVC new];
                        [weakSelf.navigationController pushViewController:onlineVC animated:YES];
                    }else if([code integerValue]==200){
                        self.onLineDataArray  = [WKOnlinePingguResultModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
                        LBEvaluationResultVC *onlineVC = [[LBEvaluationResultVC alloc] init];
                        onlineVC.dataArray = self.onLineDataArray;
                        [self.navigationController pushViewController:onlineVC animated:YES];
                    }
                }];
            }

        }
            break;
//
        case 1:{
            if (!token) {
                [self gotoLoginViewController];
            }else{
                VKStudyCardController *card = [[VKStudyCardController alloc]init];
                [self.navigationController pushViewController:card animated:YES];
            }
            break;
        }
        case 2:{

            if (!token) {
                [self gotoLoginViewController];
            }else{
                VKStudyLeaveController *card = [[VKStudyLeaveController alloc]init];
                [self.navigationController pushViewController:card animated:YES];
            }
        }
        break;

        case 3:
        {
            if (!token) {
                [self gotoLoginViewController];
            }else{
                LBCourseCollectVC *vc = [LBCourseCollectVC new];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
            
        default:
            break;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"Cell";
    LBSaomangCell *cell = [LBSaomangCell cellWithTableView:tableView];
    LBCourseOutputDTOListModel *model = self.dataArray[indexPath.row];
    cell.mycourseListModel = model;
    cell.freeIcon.hidden = YES;
    cell.priceLab.hidden = YES;
    return cell;

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [UIView new];
    
    UIImageView *icon = [[UIImageView alloc] init];
    icon.image = [UIImage imageNamed:@"wk_line"];
    [headerView addSubview:icon];

    [icon makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.size.mas_equalTo(CGSizeMake(5, 16));
        make.centerY.mas_equalTo(headerView);
    }];
    
    UILabel *titleLab = [UILabel labelWithText:@"我的课程" andTextColor:rgb(51,51,51) andName:nil andFontSize:16];
    [headerView addSubview:titleLab];
    [titleLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(icon.mas_right).mas_equalTo(9);
        make.centerY.mas_equalTo(headerView);
    }];
    

    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40*kScaleFit;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *token = [UserModel getUserModel].token;
    if (!token) {
        LBLoginVC *loginVC = [[LBLoginVC alloc] init];
        loginVC.jumpType = @"1";
        [self.navigationController pushViewController:loginVC animated:YES];
    }else{
        LBCourseOutputDTOListModel *model = self.dataArray[indexPath.row];
        
        if ([model.courseType isEqualToString:@"1"]) {//课程
            LBCoureseDetailVC *detailVC = [LBCoureseDetailVC new];
            detailVC.courseId = model.courseId;
            detailVC.type = model.courseType;
//            detailVC.courseInfo = model.courseInfo;
            [self.navigationController pushViewController:detailVC animated:YES];
        }else{                                         //2 课程包
            CourseDetailsViewController *packVC = [[CourseDetailsViewController alloc] initWithNibName:@"CourseDetailsViewController" bundle:nil];
            packVC.packId = model.courseId;
            packVC.collectType = model.courseType;
            packVC.courseInfo = model.courseInfo;
            [self.navigationController pushViewController:packVC animated:YES];
        }
        
    }
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
@end
